import Mock from "mockjs";
import type { MockParams } from "./index.d";
import MockIndex from "./mock-index";
import MockShop from "./mock-shop";

Mock.setup({
    timeout: "300",
});
const mocks = [...MockIndex, ...MockShop];
export function mockXHR() {
    let i: MockParams;
    for (i of mocks) {
        Mock.mock(new RegExp(i.url), i.type || "get", i.response);
    }
}

export function ArrSet(Arr: any[], id: string): any[] {
    let obj: any = {};
    const arrays = Arr.reduce((setArr, item) => {
        obj[item[id]] ? "" : (obj[item[id]] = true && setArr.push(item));
        return setArr;
    }, []);
    return arrays;
}
/**
 * @description: min ≤ r ≤ max  随机数
 * @param {*} Min
 * @param {*} Max
 * @return {*}
 */
export function RandomNumBoth(Min: any, Max: any) {
    var Range = Max - Min;
    var Rand = Math.random();
    var num = Min + Math.round(Rand * Range); //四舍五入
    return num;
}

/**
 * @description: 生成一个随时数组,之和是100
 * @param {*} length 返回数组长度
 * @return {*}
 */
export function generateRandomArray(length: number) {
    if (length <= 0) {
        throw new Error("Length must be a positive integer.");
    }

    let randomNumbers = [];
    let sum = 0;

    // Generate random numbers and ensure their sum is close to 100
    for (let i = 0; i < length - 1; i++) {
        let randomNumber = Math.random() * (100 - sum);
        randomNumbers.push(randomNumber);
        sum += randomNumber;
    }

    // The last number ensures the total sum is exactly 100
    randomNumbers.push(100 - sum);

    return randomNumbers.map(num => parseFloat(num.toFixed(2))); // Round to 2 decimal places
}
